#include <stdio.h>
#include <windows.h>
#include <stdint.h>


#include "include/envhook.h"
#include "include/log.h"
#include "include/pointers.h"
#include "include/thiscall.h" 
#include "include/botdata.h"
#include "include/combat.h"

/* Just a function to have some fun and test some functionality, looking for possible crashes */
void
LogSomeStuff(struct BotData *botData)
{
    int ingame = 0;
    struct RomBase *base = *BASE_PTR;

    while(1)
    {
        if(base->player != NULL)
        {
            if(ingame == 0)
            {
                ingame = 1;
                LogPlayer(botData);
            }
//            if(base->player->target == NULL)
                SelectNearestMonster(botData);
        }
        else
        {
            ingame = 0;
        }
        Sleep(1000);
    }
}

unsigned long __stdcall
MainThread(void *data __attribute__((unused)))
{
    struct BotData botData = BOTDATA_INIT;
    /* Open the logfile */
    if(LogOpen(&botData, "APPDATA", "rombot.log"))
    {
        return 1;
    }
    LogWrite(&botData, "RomBot dll loaded!");

    /* Initialize the environment mutex */
    botData.environment.mutex = CreateMutex(NULL, 0, NULL);
    if(botData.environment.mutex == NULL)
    {
        LogWrite(&botData, "Error: CreateMutex failed with %lX", GetLastError());
        LogClose(&botData);
        return 1;
    }

    /* Install the environment Hook */
    EnvHookInstall(&botData);

    /* And some test stuff ;p */
    LogSomeStuff(&botData);
    LogClose(&botData);
    return 0;
}

int __stdcall
DllMain(HINSTANCE hinstDLL __attribute__((unused)),
        DWORD fdwReason,
        LPVOID lpvReserved __attribute__((unused)))
{
    /* Starting a thread in DllMain is NOT a good idea and should be changed
     * Just doing this temporarily due to LAZY */
    if(fdwReason == DLL_PROCESS_ATTACH)
    {
        CreateThread(NULL, 0, &MainThread, NULL, 0, NULL);
    }

    return TRUE;
}
